import React, { useState } from 'react';
import { TreeSelect } from 'antd';
import { useFetchDataEffect } from '@/utils/curd';
import { getProjectTreeAll } from '@/pages/auth-manage/project-manage/service';
import { treeListToTree } from '@/pages/auth-manage/project-manage/utils';

type Props = {
  value?: any;
  placeholder?: string;
  onChange?: (data: any) => void;
};

export const changeTreeData = (treeData: any[]): any[] => {
  return treeData.map((item) => {
    /* const itemAuthCodes = item.authCodes || []; */
    const newItem = {
      ...item,
      title: item.name,
      value: item.id,
      children: item.children ? changeTreeData(item.children) : [],
    };
    return newItem;
  });
};

const SelectProject: React.FC<Props> = ({ value, placeholder, onChange }) => {
  const [list, setList] = useState<any[]>([]);

  useFetchDataEffect(
    {
      fetcher: async () => {
        const { data } = await getProjectTreeAll();
        const tree = treeListToTree(data);
        return changeTreeData(tree);
      },
      updater: setList,
    },
    [],
  );

  return (
    <TreeSelect
      showSearch
      placeholder={placeholder || '请选择项目'}
      allowClear
      treeDefaultExpandAll
      value={value}
      onChange={onChange}
      treeData={list}
      treeDataSimpleMode
    />
  );
};

export default SelectProject;
